from workflows import workflows1, workflows3, workflows5, workflows6,workflows7
from api.modelsItem.FaceItem import RoopResult, RoopItem, VideoUrlItem
from workflows import workflows2
from api.modelsItem.FaceItem import FaceInfoResponseModel, FaceDetectItem,ManyFaceRequestData
from celerytask import app
from config import redis_config
from tybase.tools.Task import TaskRunner
from fastapi import APIRouter
from api.modelsItem.many_face_video_model import RequestDataModel
from concurrent.futures import ThreadPoolExecutor
from pydantic import BaseModel, Field
import sys
sys.path.append("..")  # 也可以这样sys.path.append("../..")


roop_fast_api_app = APIRouter()
executor = ThreadPoolExecutor(max_workers=10)  # 有10个线程池,那么能在这里阻塞

# # 获得任务函数的引用
detect_faces_func = app.tasks['celerytask.tasks.detect_faces']  # 人脸检测的api流程
# 人脸验证的api流程
get_best_face_urls = app.tasks['celerytask.tasks.get_best_face_urls']
get_images_faces_celery = app.tasks['celerytask.tasks.get_images_faces']

@roop_fast_api_app.post("/vhl", response_model=RoopResult,summary="单人视频换脸")
async def create_roop_item(item: RoopItem) -> RoopResult:

    if ".gif" in item.video_url or ".gi" in item.video_url:
        task = TaskRunner.Task(workflows3.GIF_换脸,
                               {'gif_url': item.video_url,
                                '用户图片url': item.user_img_url,
                                '水印': item.shuiyin,
                                "oss_name": item.oss_name,
                                "GFPGANAmount": 100
                                }, callback=workflows1.notify)
    else:
        task = TaskRunner.Task(workflows7.视频_换脸,
                               {'视频url': item.video_url,
                                '用户图片url': item.user_img_url,
                                "帧数": item.frames,
                                '水印': item.shuiyin,
                                "oss_name": item.oss_name
                                }, callback=workflows1.notify)

    runner = TaskRunner(redis_config, workflows1.notify)
    # runner.run_task(task)
    executor.submit(runner.run_task, task)

    return RoopResult(task_id=task.id)


# 人脸解析相关的接口


@roop_fast_api_app.post("/detect_faces", response_model=FaceInfoResponseModel, summary="图片人脸坐标提取",
                        description="解析人脸的信息,索引位置从左往右")
async def detect_faces(item: FaceDetectItem):
    res = detect_faces_func.delay(item.img_url)
    res_datas = res.get(timeout=10)   # 这里有可能会超时,就会卡主,加一个time_out
    item_res_data = {
        "status": "success",
        "message": "Faces detected successfully.",
        "faces": res_datas
    }

    return item_res_data


@roop_fast_api_app.post("/many_face", summary="多人图片换脸",
                        description="根据索引位置来换脸,如果不知道索引位置就默认用0代替")
async def many_face(item: ManyFaceRequestData):
    res_data = workflows2.swap_faces_one_image(item.dict())
    print ("开始执行图片换脸,many_face")
    return res_data


from api.modelsItem.FaceItemV2 import FaceDataModel
from workflows import workflows8
@roop_fast_api_app.post("/many_face_v2", summary="多人图片换脸第二版",
                        description="直接传入图片来换脸")
async def many_face_v2(item: FaceDataModel):
    res_data = workflows8.swap_faces_one_image_v2(item.dict())
    return res_data





@roop_fast_api_app.post("/many_vhl", summary="多人视频换脸")
async def many_vhl(item: RequestDataModel):
    return workflows6.多人_视频_换脸(requests_data=item.model_dump())


# 这里开始使用新的接口,用celery异步的方式来获取

@roop_fast_api_app.post("/get_best_face_urls", summary="视频最佳人脸获取接口")
async def get_best_face_urls_api_v2(item: VideoUrlItem):
    from loguru import logger
    from celerytask import tasks
    # logger.debug(item.video_url)
    res = tasks.get_best_face_urls_v2.delay(video_url=item.video_url,oss_name=item.oss_name,
                                            notify=True)
    return {"task_id": res.id}



from pydantic import BaseModel

class ImageInput(BaseModel):
    url: str = "http://usfile.chaotuapp.com/uploads/android/user/1700650171448.jpg"
    oss_name: str = Field("ali", description="OSS服务的名称,只支持ali和qiniu")
    


@roop_fast_api_app.post("/get_images_faces", summary="图片最佳人脸获取接口")
async def get_images_face_api(item:ImageInput):
    url = item.url
    res_urls = get_images_faces_celery.apply_async(args=[url,item.oss_name]).get(timeout=15)
    ali_file = []
    for url  in res_urls:
        ali_file.append(url.split("aliyuncs.com/")[-1])
    return {"urls":res_urls,"ali_file":ali_file}